<template>
  <div class="container">
    <el-dialog
      :title="title"
      :visible="visible"
      :width="width"
      :close-on-click-modal="closeOnClickModal"
      :before-close="handleBeforeClose"
      :append-to-body:="appendToBody"
      :center="center"
      :destroy-on-close="destroyOnClose"
      :modal-append-to-body="modalAppendToBody"
      @update:visible="handleVisibleUpdate"
      @open="handleDialogOpen"
      @close="handleDialogClose"
      @closed="closeDialog"
    >
      <div
        ref="dialogContent"
        class="dialog-content"
        :style="dialogContentStyle"
      >
        <slot name="title" />
        <slot />
        <div class="footer-slot">
          <slot name="footer" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  props: {
    title: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    },
    width: {
      type: String,
      default: '50%'
    },
    closeOnClickModal: {
      type: Boolean,
      default: true
    },
    beforeClose: {
      type: Function
    },
    appendToBody: {
      type: Boolean,
      default: false
    },
    destroyOnClose: {
      type: Boolean,
      default: false
    },
    customHeight: {
      type: Number,
      default: 500
    },
    center: {
      type: Boolean,
      default: false
    },
    modalAppendToBody: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      dialogContentHeight: 0
    }
  },
  computed: {
    dialogContentStyle() {
      return {
        // maxHeight:
        //   this.dialogContentHeight < this.customHeight
        //     ? `${this.dialogContentHeight}px`
        //     : `calc(100vh - 250px)`,
        overflow:
          this.dialogContentHeight > this.customHeight ? 'auto' : 'visible'
      }
    }
  },
  methods: {
    handleVisibleUpdate(value) {
      this.$emit('update:visible', value)
    },
    handleDialogOpen() {
      this.$emit('open', true)
      this.$nextTick(() => {
        this.dialogContentHeight = this.$refs.dialogContent.scrollHeight
        console.log(this.dialogContentHeight, 'height')
      })
    },
    handleDialogClose() {
      this.resettingScroll()
      this.$emit('close', false)
    },
    closeDialog() {
      this.resettingScroll()
      this.$emit('closed', false)
    },
    resettingScroll() {
      const dialogContent = document.querySelector('.dialog-content')
      if (dialogContent) {
        dialogContent.scrollTop = 0
      }
    },
    handleBeforeClose(done) {
      if (typeof this.beforeClose === 'function') {
        this.beforeClose(done)
      } else {
        done()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.footer-slot {
  display: flex;
  justify-content: flex-end;
}
::v-deep .el-dialog__body {
  //overflow: hidden;
}
</style>
